<template>
  <div class="miaosha-management">
    <el-card>
      <div slot="header" class="clearfix">
        <span>秒杀管理</span>
        <el-button style="float: right" type="primary" @click="handleAdd" icon="el-icon-plus">
          新增秒杀活动
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <!-- <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="活动状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="未开始" :value="0"></el-option>
              <el-option label="进行中" :value="1"></el-option>
              <el-option label="已结束" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.start_time"
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div> -->

      <!-- 秒杀活动列表 -->
      <el-table :data="miaoshaList" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="活动时间" width="200">
          <template slot-scope="scope">
            <div class="time-info">
              <div>开始：{{ scope.row.start_time }}</div>
              <div>结束：{{ scope.row.end_time }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="参与商品" min-width="300">
          <template slot-scope="scope">
            <div class="product-list">
              <div v-for="product in scope.row.list" :key="product.id" class="product-item">
                <el-image 
                  :src="product.main_image" 
                  :preview-src-list="[product.main_image]"
                  style="width: 40px; height: 40px; margin-right: 8px" 
                  fit="cover">
                </el-image>
                <span>{{ product.name }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品数量" width="100">
          <template slot-scope="scope">
            <el-tag type="info">{{ scope.row.list.length }}个</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row)">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="活动开始时间" prop="start_time">
          <el-date-picker
            v-model="form.start_time"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="end_time">
          <el-date-picker
            v-model="form.end_time"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参与商品" prop="product_ids">
          <div class="product-selector">
            <div class="selector-header">
              <el-button type="primary" @click="showProductSelector">
                <i class="el-icon-plus"></i>
                选择商品
              </el-button>
              <span v-if="selectedProducts.length > 0" class="selected-count">
                已选择 {{ selectedProducts.length }} 个商品
              </span>
            </div>
            <div v-if="selectedProducts.length > 0" class="selected-products">
              <div v-for="product in selectedProducts" :key="product.id" class="selected-product">
                <el-image 
                  :src="product.main_image" 
                  style="width: 30px; height: 30px; margin-right: 8px" 
                  fit="cover">
                </el-image>
                <span class="product-name">{{ product.name }}</span>
                <el-button 
                  type="text" 
                  icon="el-icon-close" 
                  @click="removeProduct(product.id)"
                  class="remove-btn">
                </el-button>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择器 -->
    <ProductSelector
      :visible.sync="productSelectorVisible"
      :multiple="true"
      :max-selected="50"
      product-type="miaosha"
      @confirm="handleProductSelect"
    />
  </div>
</template>

<script>
import { 
  fetchMiaoshaList, 
  createMiaosha, 
  updateMiaosha, 
  deleteMiaosha 
} from '@/api/shopping'
import ProductSelector from '@/components/ProductSelector'

export default {
  name: 'MiaoshaManagement',
  components: {
    ProductSelector
  },
  data() {
    return {
      loading: false,
      miaoshaList: [],
      searchForm: {
        status: '',
        start_time: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增秒杀活动',
      isEdit: false,
      form: {
        id: '',
        start_time: '',
        end_time: '',
        product_ids: ''
      },
      rules: {
        start_time: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        end_time: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        product_ids: [
          { required: true, message: '请选择参与商品', trigger: 'change' }
        ]
      },
      selectedProducts: [],
      productSelectorVisible: false
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    // 获取秒杀列表
    async fetchList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          limit: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await fetchMiaoshaList(params)
        if (response.code === 1) {
          this.miaoshaList = response.data || []
          this.pagination.total = response.total || 0
        } else {
          this.$message.error(response.msg || '获取列表失败')
        }
      } catch (error) {
        this.$message.error('获取列表失败')
        console.error('获取秒杀列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        status: '',
        start_time: ''
      }
      this.pagination.currentPage = 1
      this.fetchList()
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增秒杀活动'
      this.isEdit = false
      this.form = {
        id: '',
        start_time: '',
        end_time: '',
        product_ids: ''
      }
      this.selectedProducts = []
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑秒杀活动'
      this.isEdit = true
      this.form = {
        id: row.id.toString(),
        start_time: row.start_time,
        end_time: row.end_time,
        product_ids: row.product_ids
      }
      this.selectedProducts = [...row.list]
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这个秒杀活动吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteMiaosha(row.id)
          if (response.code === 1) {
            this.$message.success('删除成功')
            this.fetchList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
          console.error('删除秒杀活动失败:', error)
        }
      })
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      this.$refs.form.resetFields()
      this.selectedProducts = []
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 验证时间
          if (new Date(this.form.start_time) >= new Date(this.form.end_time)) {
            this.$message.error('结束时间必须晚于开始时间')
            return
          }

          // 验证商品选择
          if (this.selectedProducts.length === 0) {
            this.$message.error('请选择参与商品')
            return
          }

          try {
            // 构建符合后端要求的数据格式
            const formData = {
              start_time: this.form.start_time,
              end_time: this.form.end_time,
              product_ids: this.selectedProducts.map(p => p.id).join(','),
              id: this.isEdit ? this.form.id : ''
            }

            // 开发调试：打印提交的数据
            console.log('提交的秒杀活动数据:', formData)
            console.log('操作类型:', this.isEdit ? '编辑' : '新增')

            const response = this.isEdit 
              ? await updateMiaosha(formData)
              : await createMiaosha(formData)

            if (response.code === 1) {
              this.$message.success(this.isEdit ? '更新成功' : '创建成功')
              this.handleClose()
              this.fetchList()
            } else {
              this.$message.error(response.msg || '操作失败')
            }
          } catch (error) {
            this.$message.error('操作失败')
            console.error('提交秒杀活动失败:', error)
          }
        }
      })
    },

    // 显示商品选择器
    showProductSelector() {
      this.productSelectorVisible = true
    },

    // 处理商品选择
    handleProductSelect(products) {
      this.selectedProducts = products
      this.form.product_ids = products.map(p => p.id).join(',')
    },

    // 移除商品
    removeProduct(productId) {
      this.selectedProducts = this.selectedProducts.filter(p => p.id !== productId)
      this.form.product_ids = this.selectedProducts.map(p => p.id).join(',')
    },

    // 获取状态类型
    getStatusType(row) {
      const now = new Date()
      const startTime = new Date(row.start_time)
      const endTime = new Date(row.end_time)

      if (now < startTime) {
        return 'info' // 未开始
      } else if (now >= startTime && now <= endTime) {
        return 'success' // 进行中
      } else {
        return 'danger' // 已结束
      }
    },

    // 获取状态文本
    getStatusText(row) {
      const now = new Date()
      const startTime = new Date(row.start_time)
      const endTime = new Date(row.end_time)

      if (now < startTime) {
        return '未开始'
      } else if (now >= startTime && now <= endTime) {
        return '进行中'
      } else {
        return '已结束'
      }
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.fetchList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchList()
    }
  }
}
</script>

<style scoped>
.miaosha-management {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.time-info {
  font-size: 12px;
  line-height: 1.4;
}

.product-list {
  max-height: 200px;
  overflow-y: auto;
}

.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-selector {
  width: 100%;
}

.selector-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.selected-count {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.selected-products {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  background-color: #fafafa;
}

.selected-product {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px;
  background-color: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  transition: all 0.3s;
}

.selected-product:hover {
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.1);
}

.selected-product:last-child {
  margin-bottom: 0;
}

.product-name {
  flex: 1;
  margin-right: 8px;
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.remove-btn {
  color: #f56c6c;
  padding: 0;
  min-width: auto;
}

.remove-btn:hover {
  color: #f56c6c;
  background-color: #fef0f0;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>
